#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SeqListInit(SL* ps)
{
	ps->data = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLCapacitycheck(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->data, newcapacity*sizeof(SLDataType));
		if (tmp != NULL)
		{
			ps->data = tmp;
			ps->capacity = newcapacity;
		}
		else
		{
			printf("realloc fail\n");
			exit(-1);
		}
	}
}

void SeqListPushBack(SL* ps, SLDataType x)
{
	SLCapacitycheck(ps);
	ps->data[ps->size] = x;
	ps->size++;
}

void SeqListPrint(SL* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

void SeqListDestory(SL* ps)
{
	free(ps->data);
	ps->data = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SeqListPopBack(SL* ps)
{
	assert((ps->size) > 0);
	ps->size--;
}

void SeqListPushFront(SL* ps, SLDataType x)
{
	SLCapacitycheck(ps);
	int end = ps->size-1;
	while (end>=0)
	{
		ps->data[end+1] = ps->data[end];
		end--;
	}
	ps->data[0] = x;
	ps->size++;
}

void SeqListPopFront(SL* ps)
{
	assert(ps->size > 0);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->data[begin - 1] = ps->data[begin];
		begin++;
	}
	ps->size--;
}

void SeqListPush(SL* ps, int pos, SLDataType x)
{
	assert(pos >= 0 && pos <= ps->size);
	SLCapacitycheck(ps);
	int end = ps->size;
	while (end>=pos)
	{
		ps->data[end+1] = ps->data[end];
		end--;
	}
	ps->data[pos] = x;
	ps->size++;
}

void SeqListPop(SL* ps, int pos)
{
	assert(pos >= 0 && pos < ps->size);
	while (pos < ps->size)
	{
		ps->data[pos] = ps->data[pos + 1];
		pos++;
	}
	ps->size--;
}

int SeqListFind(SL* ps, SLDataType x)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
		{
			return i;
		}
	}
	if (ps->size == i)
		return -1;
}

